const Result = require("../utils/result");
const jwt = require("jsonwebtoken");
const key = "xiaohuai"
const authFilter = (req, res, next) => {
  try {
    const { authorization } = req.headers; //headers 里面的所有key都会是小写

    if (!authorization) return res.json(Result.fail("authorization错误"));
    const data = jwt.verify(authorization, key); //{"user_name":"admin","iat":1635349069,"exp":1635435469}
    next();
  } catch (err) {
    res.json(Result.error(err));
  }
};
const getTokenUser = (req) => {
  try {
    const { authorization } = req.headers; //headers 里面的所有key都会是小写
    if (!authorization) return {};
    return jwt.verify(authorization, key); //{"user_name":"admin","iat":1635349069,"exp":1635435469}
  } catch (err) {
    return {};
  }
};
const isAdmin = (role) => {
  return role && (role == '1' || role == '管理员')
}

module.exports = {
  authFilter,
  getTokenUser,
  isAdmin
};